import 'dart:convert';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/dao/user_info_dao.dart';
import 'package:changxindianzishangwu/else/lib/common/index.dart';
import 'package:changxindianzishangwu/model/dynamic_media_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/pages/my/set_autograph_page.dart';
import 'package:changxindianzishangwu/pages/my/set_easyid_page.dart';
import 'package:changxindianzishangwu/pages/my/set_nickname_page.dart';
import 'package:changxindianzishangwu/pages/my/zxing_page.dart';
import 'package:changxindianzishangwu/provider/user.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/head_url.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/universal_view.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:changxindianzishangwu/widget/crop_image_route.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/style/picker_style.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart' as Intent;
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_user_full_info.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_value_callback.dart';
import 'package:tencent_im_sdk_plugin/tencent_im_sdk_plugin.dart';

///我的=》头部=》用户信息
class UserInfoPage extends StatefulWidget {
  UserInfoPage({Key key}) : super(key: key);

  @override
  _UserInfoPageState createState() => _UserInfoPageState();
}

class _UserInfoPageState extends State<UserInfoPage> {
  UserInfo _userinfo;
  var sex;
  var _lights = false;

  @override
  void initState() {
    super.initState();
  }

  _imagesSelect(imageSource) async {
    String filePath=await Intent.Get.to(CropImageRoute(imageSource));
    if(ObjectUtil.isEmptyString(filePath))return;
    _updatePhoto(filePath);

  }


  ///上传图片到服务
  Future<void> _updatePhoto(String filePath) async {
    print('更换头像 本地地址$filePath');
    if (filePath.isEmpty) {
      toast("头像地址为空");
      return;
    }

    EasyLoading.show(status: "修改头像中...");

    FormData formData = FormData();
    formData.files.add(MapEntry(
        "files",
        MultipartFile.fromFileSync(filePath,
            filename:
                "photo_${new DateTime.now().millisecondsSinceEpoch}.png")));
    DynamicMediaModel value = await UpLoadFileDao.addFile(formData);
    if (value.resultCode == 1) {
      print('返回数据:${json.encode(value)}');
      setState(() {
        _avatar = value.data.images[0].oUrl;
      });
      print('返回头像${json.encode(value.data.images[0])}');
      String path = value.data.images[0].oUrl;
      print('返回图片$path');
      _updateUserAvatar(path);
    } else {
      showToast("媒体上传失败");
    }

  }

  _handleCameraAndMic() async {
    // 申请权限

    bool a = await await Permission.photos.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      showToast("请打开图库权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }
  }

  String _avatar = "";

  @override
  Widget build(BuildContext context) {
    _userinfo = getUserInfo();
    V2TimUserFullInfo info = Provider.of<UserModel>(context).info;
    print('---into----${json.encode(info)}');
    _avatar = _avatar.isEmpty
        ? ((info.faceUrl != null && info.faceUrl.isEmpty)
            ? HEADER_URL
            : info.faceUrl)
        : _avatar;
    try {
      if (info.gender == 2) {
        sex = "女";
      } else {
        sex = "男";
      }
    } catch (e) {
      Future.delayed(Duration(seconds: 1));
      return Scaffold(
        appBar: AppBar(
          elevation: 0,
        ),
        body: Center(
          child: Text("页面错误"),
        ),
      );
    }

    return Scaffold(
      appBar: TopAppBar(context, "个人信息"),
      body: ListView(
        children: [
          Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: 10),
            child: Column(
              children: <Widget>[
                _changeFaceUrl(), //修改头像
                _line(),
                _itemInfo("昵称", info.nickName, () {
                  Intent.Get.to(() => SetNicknamePage(
                        name: info.nickName,
                      )).then((value) => {});
                }),
                _line(),
                _changeSex(context), //修改性别
                _line(),
                _itemInfo("个性签名", info.selfSignature, () {
                  Intent.Get.to(
                      () => SetAutographPage(name: info.selfSignature));
                }),
              ],
            ),
          ),
          Container(
              color: Colors.white,
              margin: EdgeInsets.only(top: 10),
              child: Column(
                children: <Widget>[
                  _itemInfo("自语号", _userinfo.account.toString(), () {
                    Intent.Get.to(
                            SetEasyIdPage(name: _userinfo.account.toString()))
                        .then((value) {
                      setState(() {});
                    });
                  },longFuction: (){
                    Clipboard.setData(ClipboardData(text:  _userinfo.account));
                    toast("自语号已复制到剪贴板");
                  }),
                  _line(),
                  _itemInfo("我的二维码", "".toString(), () {
                    Intent.Get.to(ZxingPage());
                  }),
                ],
              )),
        ],
      ),
    );
  }

  //
  // Future _openModalBottomSheet() async {
  //   final option = await showModalBottomSheet(
  //       context: context,
  //       builder: (BuildContext context) {
  //         return Container(
  //           height: 200.0,
  //           child: Column(
  //             children: <Widget>[
  //               ListTile(
  //                 title: Text('拍照', textAlign: TextAlign.center),
  //                 onTap: () {
  //                   _photoSelect();
  //                   Navigator.pop(context, '拍照');
  //                 },
  //               ),
  //               ListTile(
  //                 title: Text('从相册选择', textAlign: TextAlign.center),
  //                 onTap: () {
  //                   _imagesSelect();
  //                   Navigator.pop(context, '从相册选择');
  //                 },
  //               ),
  //               ListTile(
  //                 title: Text('取消', textAlign: TextAlign.center),
  //                 onTap: () {
  //                   Navigator.pop(context, '取消');
  //                 },
  //               ),
  //             ],
  //           ),
  //         );
  //       });
  //
  //   print(option);
  // }
  void _selectAction() async {
    int index = await showDialog(context: context, title: '修改头像');
    await _handleCameraAndMic();

    if (index == 1) {
      _imagesSelect(ImageSource.camera);
      // Navigator.pop(context, '拍照');
    }
    if (index == 2) {
      _imagesSelect(ImageSource.gallery);
      // Navigator.pop(context, '从相册选择');
    }
  }

  Future<int> showDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        children: [
          actionItem(
              context: context,
              index: 1,
              title: '拍摄',
              color: AppColor.colorDialog),
          actionItem(
              context: context,
              index: 2,
              title: '从相册选择',
              isLastOne: true,
              color: AppColor.colorDialog),
        ]);
  }

  InkWell _changeFaceUrl() {
    return InkWell(
      onTap: () {
        _selectAction();
      },
      child: ListTile(
        leading: Text(
          "头像",
          style: TextStyle(fontSize: ScreenUtil().setSp(15)),
        ),
        title: Container(
          alignment: Alignment.centerRight,
          child: HeadView(
              _avatar, ScreenUtil().setWidth(50), ScreenUtil().setWidth(50)),
        ),
        trailing: Icon(Icons.keyboard_arrow_right),
      ),
    );
  }

  InkWell _changeSex(BuildContext context) {
    return InkWell(
      onTap: () {
        print("修改性别-----------------------------");

        Pickers.showSinglePicker(context,
            pickerStyle: PickerStyle(
                commitButton: Container(
              alignment: Alignment.center,
              padding: const EdgeInsets.only(left: 12, right: 22),
              child: Text('确定',
                  style: TextStyle(
                      color: Theme.of(context).unselectedWidgetColor,
                      fontSize: 16.0)),
            )),
            data: ['男', '女'],
            onConfirm: (p, position) {
              position = position + 1;
              EasyLoading.show(status: "修改中...");
              TencentImSDKPlugin.v2TIMManager
                  .setSelfInfo(
                userFullInfo: V2TimUserFullInfo.fromJson(
                  {
                    "gender": position,
                  },
                ),
              )
                  .then((value) {
                print('---------IM修改成功');
                if (value.code == 0) {
                  onSelfInfoUpdated();
                  _updateUserInfo("$position");
                } else {
                  EasyLoading.dismiss();
                }
              });

              //todo 需要走服务器流程
              sex = p;
            },
            selectData: sex,
            onChanged: (p, position) {
              print(sex);
            });
      },
      child: ListTile(
        leading: Text(
          "性别",
          style: TextStyle(fontSize: ScreenUtil().setSp(15)),
        ),
        title: Container(
          alignment: Alignment.centerRight,
          height: ScreenUtil().setHeight(50),
          width: ScreenUtil().setWidth(50),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(4),
          ),
          child: Text(
            sex ?? "",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(15),
                color: Color.fromRGBO(153, 153, 153, 1)),
          ),
        ),
        trailing: Icon(Icons.keyboard_arrow_right),
      ),
    );
  }

  Divider _line() {
    return Divider(
      height: 1,
      indent: ScreenUtil().setWidth(10),
      color: Color.fromRGBO(248, 248, 248, 1),
      thickness: ScreenUtil().setHeight(1),
    );
  }

  Widget _itemInfo(String title, String content, Function function,{Function longFuction}) {
    return InkWell(
      onLongPress:longFuction ,
      onTap: () {
        function();
      },
      child: ListTile(
        leading: Text(
          title,
          style: TextStyle(fontSize: ScreenUtil().setSp(15)),
        ),
        title: Container(
          alignment: Alignment.centerRight,
          height: ScreenUtil().setHeight(50),
          width: ScreenUtil().setWidth(50),
          decoration: BoxDecoration(),
          child: Text(
            content ?? "",
            style: TextStyle(
                fontSize: ScreenUtil().setSp(15),
                color: Color.fromRGBO(153, 153, 153, 1)),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        trailing: Icon(Icons.keyboard_arrow_right),
      ),
    );
  }

  void onSelfInfoUpdated() async {
    //自己信息更新，从新获取自己的信息；
    V2TimValueCallback<String> usercallback =
        await TencentImSDKPlugin.v2TIMManager.getLoginUser();
    V2TimValueCallback<List<V2TimUserFullInfo>> infos = await TencentImSDKPlugin
        .v2TIMManager
        .getUsersInfo(userIDList: [usercallback.data]);
    if (infos.code == 0) {
      Provider.of<UserModel>(context, listen: false).setInfo(infos.data[0]);
    }
  }

  _updateUserInfo(String content) async {
    try {
      UserInfoModel userInfoModel =
          await UserInfoDao.updateUserInfo("sex", content);
      EasyLoading.dismiss();

      if (userInfoModel.resultCode == 0) {
        toast("修改失败");
        return;
      }
      toast("修改成功");
    } catch (e) {
      print(e);
      _error();
    }
  }

  _updateUserAvatar(String content) async {
    try {
      TencentImSDKPlugin.v2TIMManager
          .setSelfInfo(
              userFullInfo: V2TimUserFullInfo.fromJson({
        "faceUrl": content,
      }))
          .then((value) async {
        if (value.code == 0) {
          UserInfoModel userInfoModel =
              await UserInfoDao.updateUserInfo("avatar", content);
          if (userInfoModel.resultCode == 0) {
            toast("修改成功");
            return;
          }
          EasyLoading.dismiss();
          toast("修改成功");
        }
      });
    } catch (e) {
      print(e);
      _error();
    }
  }

  void _error() {
    EasyLoading.dismiss();

  }

  @override
  void dispose() {
    // TODO: implement dispose
    EasyLoading.dismiss();
    super.dispose();
  }
}
